﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using WpfApp.Tools.Utils;

namespace WpfApp.View.LineManage
{
    /// <summary>
    /// WD_UpdateStationManage.xaml 的交互逻辑
    /// </summary>
    public partial class WD_UpdateStationManage : Window
    {
        public DataRowView DRV;
        int intOldsiteID;//站点主键ID
        DataTable dt;//表格数据(全部)
        DataTable dtOld;//临时保存旧数据（选中邻居站点）
        BLL.UCStationManage.UC_StationManageClient myStationManage = new BLL.UCStationManage.UC_StationManageClient();
        public WD_UpdateStationManage(DataRowView drv)
        {
            InitializeComponent();
            DRV = drv;
        }
        /// <summary>
        /// 页面加载时
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void WD_UpdateStationManage_Loaded(object sender, RoutedEventArgs e)
        {
            #region 绑定省份信息
            DataTable drProvince = myStationManage.SelectProvince().Tables[0];
            cbo_pro.ItemsSource = drProvince.DefaultView;
            cbo_pro.DisplayMemberPath = "proName";
            cbo_pro.SelectedValuePath = "proID";
            #endregion
            //获取主键
            intOldsiteID = Convert.ToInt32(DRV.Row["siteID"]);
            //绑定表格数据
            dt = myStationManage.USelectStationManage(intOldsiteID).Tables[0];
            dgSite.ItemsSource = dt.DefaultView;
            GetData();//页面数据回填
        }
        public void GetData()
        {
            #region 页面数据回填
            txt_Station.Text = (DRV.Row["siteName"]).ToString();
            txt_short_code.Text = (DRV.Row["shortCode"]).ToString();
            txt_full_code.Text = (DRV.Row["fullCode"]).ToString();
            cbo_pro.SelectedValue = Convert.ToInt32((DRV.Row["proID"]));
            //获取邻居站点数据
            dtOld = myStationManage.SelectSiteBySiteId(intOldsiteID).Tables[0];
            //回填邻居信息
            for (int i = 0; i < dt.Rows.Count; i++)//dt 代表表格数据（全部数据）
            {
                // 循环表格数据
                for (int j = 0; j < dtOld.Rows.Count; j++)//一部分数据
                {
                    if (Convert.ToInt32(dt.Rows[i]["siteID"]) == Convert.ToInt32(dtOld.Rows[j]["neighborSiteID"]))
                    {
                        //绑定表格数值（单元格数值赋值）
                        dt.Rows[i]["chked"] = true;
                        dt.Rows[i]["distance"] = dtOld.Rows[j]["distance"];
                    }
                }
            }

            #endregion
        }
        /// <summary>
        /// 重置按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Reset_Click(object sender, RoutedEventArgs e)
        {
            GetData();//页面数据回填（目的是让数据回到最初的状态）
        }
        /// <summary>
        /// 保存修改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Affirm_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                using(TransactionScope scope=new TransactionScope())
                {
                    int intIcount = 0;//记录新增数据
                    //获取页面数据判断不能为空
                    if (cbo_pro.SelectedValue != null && !string.IsNullOrEmpty(txt_Station.Text) && !string.IsNullOrEmpty(txt_short_code.Text) && !string.IsNullOrEmpty(txt_full_code.Text))
                    {
                        //第一步：站点表（执行修改）
                        string siteName = txt_Station.Text.ToString().Trim();
                        string shortCode = txt_short_code.Text.ToString().Trim();
                        string fullCode = txt_full_code.Text.ToString().Trim();
                        int intproId = Convert.ToInt32(cbo_pro.SelectedValue);
                        Boolean blstopNo = false;
                        //（执行修改）
                        int intCount = myStationManage.UpdateStation(siteName, shortCode, fullCode, intproId, blstopNo, intOldsiteID);
                        if (intCount > 0)
                        {
                            //第二步：邻居站点表
                            //1、新增之前（批量删除）
                            int intDCount = 0;
                            for (int i = 0; i < dtOld.Rows.Count; i++)
                            {
                                //主键删除邻居站点数据
                                int intSiteNeighborId = Convert.ToInt32(dtOld.Rows[i]["siteNeighborID"]);
                                //（批量删除）
                                myStationManage.DeleteNeighborSite(intSiteNeighborId);
                                intDCount++;
                            }
                            //判断删除是否成功
                            if (dtOld.Rows.Count == intDCount)
                            {
                                //2、：新增现在邻居表数据
                                #region 第二步：新增最新的站点 
                                for (int i = 0; i < dgSite.Items.Count; i++)
                                {
                                    if (Convert.ToBoolean(dt.Rows[i]["chked"]) == true && ((DataRowView)dgSite.Items[i]).Row["distance"].ToString() != null)
                                    {
                                        //(新增邻居站点)
                                        int intNeighborSiteId = Convert.ToInt32(((DataRowView)dgSite.Items[i]).Row["siteID"]);//邻居站点ID
                                        Decimal decdistance = Convert.ToDecimal(((DataRowView)dgSite.Items[i]).Row["distance"]);//距离
                                        //执行新增
                                        intIcount = Convert.ToInt32(myStationManage.InsertNeighborSite(intOldsiteID, intNeighborSiteId, decdistance));

                                    }
                                }
                                #endregion

                            }
                        }
                        //判断邻居站点数据是否新增成功
                        if (intIcount > 0)
                        {
                            MessageBoxResult dr = MessageBox.Show("修改数据成功！", "系统提示", MessageBoxButton.OKCancel, MessageBoxImage.Information);//弹出确定对话框
                            if (dr == MessageBoxResult.OK)
                            {
                                this.Close();//关闭当前窗口
                            }
                        }

                    }
                    else
                    {
                        MessageBox.Show("页面数据不能为空！", "系统提示", MessageBoxButton.OK, MessageBoxImage.Error);//弹出确定对话框
                    }


                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                MessageBox.Show("数据异常！", "系统提示", MessageBoxButton.OK, MessageBoxImage.Error);//弹出确定对话框
            }
        }
        /// <summary>
        /// 取消按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Cancel_Click(object sender, RoutedEventArgs e)
        {
            MessageBoxResult dr = MessageBox.Show("退出界面数据将不保留。", "系统提示", MessageBoxButton.OKCancel, MessageBoxImage.Question);//弹出确定对话框
            if (dr == MessageBoxResult.OK)//如果点了确定按钮
            {
                this.Close();
            }
        }
        /// <summary>
        /// //站点文本改变事件（绑定简码和拼音码）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txt_Station_SelectionChanged(object sender, RoutedEventArgs e)
        {
            txt_short_code.Text= PublicStaticMothd.GetChineseSpell(txt_Station.Text.Trim());//引用拼音简码方法 
            txt_full_code.Text = (new PublicStaticMothd.PinYin()).GetABC(txt_Station.Text);
        }
        /// <summary>
        ///  CheckBox状态控制
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgSite_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (Convert.ToBoolean(dt.Rows[0]["chked"]) == false)
            {
                dt.Rows[0]["chked"] = true;
            }
            else
            {
                dt.Rows[0]["chked"] = false;
            }
        }
    }
}
